package gases.as3.librarys.compnents.ui.control
{
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.utils.Dictionary;
	
	import gases.as3.librarys.compnents.events.IconCellListEvent;
	import gases.as3.librarys.compnents.skin.data.BaseSkin;
	import gases.as3.librarys.compnents.skin.data.IconCellListSkin;
	import gases.as3.librarys.compnents.ui.GSkinBox;
	import gases.as3.librarys.compnents.ui.GUIComepments;
	
	public class IconCellList extends GUIComepments
	{
		/**
		 *图标格子组 ,宽度一定，高度一定
		 * @param rows 行
		 * @param cols 列
		 * @param hgap 横 间隔
		 * @param vgap 竖 间隔
		 * @param cellWidth 单个格子宽度
		 * @param cellHeight 单个格子高度
		 * 
		 */		
		public function IconCellList(rows:int=1, cols:int=0, hgap:int=0, vgap:int=0,cellWidth:Number = 30,cellHeight:Number = 30)
		{
			_rows =			 rows;
			_cols =			 cols;
			_hgap =			 hgap;
			_vgap =			 vgap;
			_cellWidth =   	 cellWidth;
			_cellHeight =	 cellHeight;
			super();
		}
		
		override protected function initialization():void
		{
			this.doubleClickEnabled = true;
			cellIndexDict = new Dictionary();
			_sprite = new Sprite();
			this.addChild(_sprite);
			_background = new GSkinBox();
			this.addChildAt(_background,0);
			_background.mouseChildren = false;
			_background.mouseEnabled = false;
			addEventListeners();
		}
		
		override public function set skin(value:BaseSkin):void
		{
			super.skin = value;
			_souceSkin = value as IconCellListSkin;
			_background.source = _souceSkin.list_bg;
		}
		
		override public function get height():Number
		{
			return _rows * _cellHeight + (_rows - 1) * _vgap;
		}
		
		override public function get width():Number
		{
			return _cols * _cellWidth + (_cols - 1) * _hgap;
		}
		
		override public function dispose():void
		{
			for each(var obj:Object in cellIndexDict)
			{
				obj = null;
			}
			cellIndexDict = null;
			this.graphics.clear();
			if(_sprite)
			{
				if(this.contains(_sprite))
				{
					_sprite.graphics.clear();
					this.removeChild(_sprite);
				}
			}
			super.dispose();
			
		}
		
		/**
		 *更新单个 格子
		 * @param index 格子index
		 * @param bmd 图标的bitmapdata
		 * @param id 图标的id，可有可无,推荐使用
		 * 
		 */		
		public function updateDrawCell(index:int,bmd:BitmapData,id:String = ""):void
		{
			var obj:Object = {bmd:bmd,id:id};
			cellIndexDict[index] = obj;
			drawAllCell();
		}
		
		/**
		 *更新所有的格子  
		 * @param array 数组里面的都是object，分别有index,id,bmd属性
		 * 
		 */		
		public function updateDrawAllCell(array:Array):void
		{
			for each(var cell:Object in cellIndexDict)
			{
				cell = null;
			}
			cellIndexDict = new Dictionary();
			this.graphics.clear();
			for(var i:int = 0;i<array.length;i++)
			{
				var obj:Object = array[i];
				var index:int = obj.index;
				var bmd:BitmapData = obj.bmd as BitmapData;
				var id:String = obj.id as String;
				
				var object:Object = {bmd:bmd,id:id};
				cellIndexDict[index] = object;
			}
			drawAllCell();
		}
		
		/**
		 *删除单个格子 
		 * @param index
		 * 
		 */		
		public function delCell(index:int):void
		{
			if(cellIndexDict[index])
			{
				delete cellIndexDict[index];
			}
			drawAllCell();
		}
		
		public function delAllCell():void
		{
			for each(var obj:Object in cellIndexDict)
			{
				obj = null;
			}
			cellIndexDict = new Dictionary();
			drawAllCell();
		}
		
		/**
		 *画所有的格子 
		 * 
		 */		
		public function drawAllCell():void
		{
			clearBitmapdata();
			var maxIndex:int = _rows * _cols;
			for(var i:int = 0; i < maxIndex; i++)
			{
				var obj:Object = cellIndexDict[i];
				if(obj)
				{
					var bmd:BitmapData = obj.bmd as BitmapData;
					var id:String = obj.id as String;
					drawCell(i,bmd,id);
				}
			}
		}
		
		private function addEventListeners():void
		{
			_sprite.addEventListener(MouseEvent.CLICK,clickHandler);
			_sprite.addEventListener(MouseEvent.MOUSE_DOWN,clickHandler);
			_sprite.addEventListener(MouseEvent.DOUBLE_CLICK,clickHandler);
			_sprite.addEventListener(MouseEvent.MOUSE_OUT,cellOut);
			_sprite.addEventListener(MouseEvent.MOUSE_OVER,cellOver);
			_sprite.addEventListener(MouseEvent.MOUSE_UP,cellUp);
		}
		
		private function clickHandler(e:MouseEvent):void
		{
			var curIndex:int = calculationGridIndex(this.mouseX,this.mouseY);
			if(curIndex < 0)
			{
				return;
			}
			var obj:Object = cellIndexDict[curIndex];
			if(obj)
			{
				_curSelectIndex = curIndex;
				var id:String = obj.id;
				if(e.type == MouseEvent.CLICK)
				{
					this.dispatchEvent(new IconCellListEvent(IconCellListEvent.CELL_CLICK,id));
				}
				else if(e.type == MouseEvent.DOUBLE_CLICK)
				{
					this.dispatchEvent(new IconCellListEvent(IconCellListEvent.CELL_DOUBLE_CLICK,id));
				}
				else if(e.type == MouseEvent.MOUSE_DOWN)
				{
					this.dispatchEvent(new IconCellListEvent(IconCellListEvent.CELL_DOWN,id));
				}
			}
		}
		
		private function cellUp(e:MouseEvent):void
		{
			this.dispatchEvent(new IconCellListEvent(IconCellListEvent.CELL_UP));
		}
		
		private function cellOver(e:MouseEvent):void
		{
			var curIndex:int = calculationGridIndex(this.mouseX,this.mouseY);
			if(curIndex < 0 || curIndex == _curOverIndex)
			{
				return;
			}
			_curOverIndex = curIndex;
			var obj:Object = cellIndexDict[curIndex];
			if(obj)
			{
				var id:String = obj.id;
				this.dispatchEvent(new IconCellListEvent(IconCellListEvent.CELL_OVER,id));
			}
		}
		
		private function cellOut(e:MouseEvent):void
		{
			_curOutIndex = _curOverIndex;
			_curOverIndex = -1;
			this.dispatchEvent(new IconCellListEvent(IconCellListEvent.CELL_OUT));
		}
		
		/**
		 *画单个格子的位图 
		 * @param index 格子index
		 * @param bmd 图标的bitmapdata
		 * @param id 图标的id，可有可无,推荐使用
		 * 
		 */		
		private function drawCell(index:int,bmd:BitmapData,id:String = ""):void
		{
			var point:Point = calculationGridPosition(index);
			if(point == null)
			{
				return;
			}
			var matrix:Matrix = new Matrix();
			matrix.tx = point.x;
			matrix.ty = point.y;
			_sprite.graphics.beginBitmapFill(bmd,matrix);
			_sprite.graphics.drawRect(point.x,point.y,_cellWidth,_cellHeight);
			_sprite.graphics.endFill();
			matrix = null;
		}
		
		/**
		 * 计算格子坐标 （返回最左上角的点）
		 */		
		private function calculationGridPosition(gridIndex:int):Point
		{
			var ret:Point = new Point();
			if(gridIndex < 0 || gridIndex >= (_rows * _cols))
			{
				return null;
			}
			var gridRowIndex:int = Math.floor(gridIndex / _cols);
			var gridCellIndex:int = Math.abs(gridIndex % _cols);
			ret.x = gridCellIndex * (_cellWidth + _hgap);
			ret.y = gridRowIndex * (_cellHeight + _vgap);
			return ret;
		}
		
		/**
		 * 计算格子位置（从0开始，返回当前格子位置）
		 */		
		private function calculationGridIndex(gridX:Number,gridY:Number):int
		{
			var gridIndex:int = -1;
			var xBool:Boolean = hasInHGapOrVGap(gridX,"x");
			var yBool:Boolean = hasInHGapOrVGap(gridY,"y");
			if(xBool || yBool)
			{
				return gridIndex;
			}
			var gridCellNum:int = Math.floor(gridX / (_cellWidth + _hgap));
			var gridRowNum:int = Math.floor(gridY / (_cellHeight + _vgap));
			gridIndex = gridRowNum * _cols + gridCellNum;
			if(gridIndex >= _rows * _cols)
			{
				gridIndex = -1;
			}
			return gridIndex;
		}
		
		private function hasInHGapOrVGap(postion:Number,xory:String):Boolean
		{
			var ret:Boolean = false;
			var roworcol:int = xory == "x" ? _rows:_cols;
			var horvgaps:int = xory == "x" ? _hgap:_vgap;
			var heightorwidth:Number = xory == "x" ? _cellWidth:_cellHeight;
			
			for(var i:int = 0; i < roworcol;i++)
			{
				var min:Number;
				var max:Number;
				min = (i + 1) * heightorwidth + i * horvgaps;
				max = i == roworcol - 1 ? (i + 1) * heightorwidth + i * horvgaps:(i + 1) * heightorwidth + (i+1) * horvgaps;
				
				if(postion >= min && postion <= max)
				{
					ret = true;
				}
			}
			return ret;
		}
		
		private function clearBitmapdata():void
		{
			_sprite.graphics.clear();
		}
		
		private var _rows:int;
		private var _cols:int;
		private var _hgap:int;
		private var _vgap:int;
		private var _cellWidth:Number;
		private var _cellHeight:Number;
		
		private var _souceSkin:IconCellListSkin;
		/**
		 *背景格子 
		 */		
		private var _background:GSkinBox;
		
		/**
		 *用于装载图标的容器 
		 */		
		private var _sprite:Sprite;
		/**
		 *保存当前位置的图标id,图标bmd
		 */		
		private var cellIndexDict:Dictionary;
		
		/**
		 *当前移进的Index 
		 */		
		private var _curOverIndex:int = -1;
		/**
		 *当前移出的Index 
		 */		
		private var _curOutIndex:int = -1 ;
		/**
		 *当前选择的Index 
		 */		
		private var _curSelectIndex:int = -1;
	}
}